package com.example.xaop.proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author xingyulai
 * @date 2024/3/8 4:28 PM
 * @description
 **/
public class CglibProxyExample implements MethodInterceptor {

    //目标类类型
    private Class<?> targetClass;

    //为目标类生成代理对象
    public Object createProxy(Class<?> targetClass) {

        this.targetClass = targetClass;
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(this.targetClass);
        //设置回调方法 MethodInterceptor--->Callback
        enhancer.setCallback(this);
        //创建并返回代理对象
        return enhancer.create();

    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

        Object result = proxy.invokeSuper(obj, args);

        // 在方法调用后执行的逻辑
        System.out.println("After method call: " + method.getName());
        return result;

    }

    public static void main(String[] args) {

        CglibProxyExample proxy = new CglibProxyExample();

        Class<?> targetClazz=SomeBusinessClass.class;

        SomeBusinessClass business = (SomeBusinessClass) proxy.createProxy(targetClazz);
        //通过代理对象调用方法
        business.someMethod();
    }
}

class SomeBusinessClass {
    public void someMethod() {
        System.out.println("Executing someMethod()");
    }
}
